//
// Created by tang on 2022/1/12.
//

#include "app_config_view.hpp"
#include "gui/dialog_names.h"
#include "gui/ui_component.hpp"
#include "imgui/imgui.h"
#include "imgui/imgui_stdlib.h"
#include "imgui/IconsFontAwesome4.h"
#include "app/app_base.hpp"
#include "data/app_config.hpp"
#include "event/events.hpp"
#include "fmt/format.h"
#include "gui/controls/custom_controls.hpp"
#include "utils/os_utils.hpp"

struct AppConfigData
{
    bool is_first_frame;
};

AppConfigView::AppConfigView() : d{ new AppConfigData }
{
    d->is_first_frame = true;
}

AppConfigView::~AppConfigView()
{
    delete d;
}

void AppConfigView::Menu() const
{
    if (ImGui::BeginMenu(ICON_FA_COGS " 设置"))
    {
        if (ImGui::MenuItem(ICON_FA_COG " 程序设置"))
        {
            App->ShowDialog(APP_SETTING_DIALOG_NAME);
        }
        if (ImGui::MenuItem(ICON_FA_DATABASE " 数据库设置", nullptr, false, App->Sql()->GetConfig() != nullptr))
        {
            // TODO:
        }
        if (ImGui::MenuItem(ICON_FA_TAG " 标签管理"))
        {
            App->ShowDialog(TAG_MANAGEMENT_DIALOG_NAME);
        }
        if (ImGui::MenuItem(ICON_FA_FILE_TEXT " 模板管理"))
        {
            App->ShowDialog(TEMPLATE_EDITOR_DIALOG_NAME);
        }
        ImGui::Separator();
        if (ImGui::MenuItem(ICON_FA_RECYCLE " 重启程序"))
        {
            RestartApp();
        }
        if (ImGui::MenuItem(ICON_FA_TIMES " 退出程序"))
        {
            App->Exit();
        }
        ImGui::EndMenu();
    }
}

void AppConfigView::Dialog() const
{
    ImGui::PushStyleColor(ImGuiCol_FrameBg , IM_COL32 (0,0,0,0));
    ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8,8));
    ImGui::BeginChild("##SettingContent", ImVec2{-1, -ImGui::GetTextLineHeightWithSpacing() * 1.5f }, ImGuiChildFlags_FrameStyle);
    ImGui::PopStyleColor();
    ImGui::PopStyleVar();
    ImGui::Spacing();
    Config::RenderConfigurationsView(d->is_first_frame);
    ImGui::Spacing();
    ImGui::EndChild();
    if (d->is_first_frame)
    {
        d->is_first_frame = false;
    }

    ImGui::WindowBottomButtons(2, default_ok_cancel_button_text, [this](int i, void*)
        {
            if (i == 0) // ok
            {
                Config::ViewClose(true);
                Config::Sync(); // write to config file
                App->Bus()->postpone(AppEvent::AppConfigEvent{});
            }
            else
            {
                Config::ViewClose(false);
            }
            d->is_first_frame = true;
            ImGui::CloseCurrentPopup();
        }, nullptr);
}

unsigned int AppConfigView::Flags() const
{
    return eDialog | eMenu;
}

void AppConfigView::RenderContent(ComponentFlag flag)
{
    if (flag == eMenu)
        Menu();
    else if (flag == eDialog)
        Dialog();
}

const char* AppConfigView::GetName(ComponentFlag flag)
{
    if (flag & eDialog)
        return MODAL_DIALOG_NAME(APP_SETTING_DIALOG_NAME);
    return nullptr;
}
